(function (jQuery) {
    let postDirectoryBuild = function () {
        let postChildren = function children(childNodes, reg) {
                let result = [],
                    isReg = typeof reg === 'object',
                    isStr = typeof reg === 'string',
                    node, i, len;
                for (i = 0, len = childNodes.length; i < len; i++) {
                    node = childNodes[i];
                    if ((node.nodeType === 1 || node.nodeType === 9) &&
                        (!reg ||
                            isReg && reg.test(node.tagName.toLowerCase()) ||
                            isStr && node.tagName.toLowerCase() === reg)) {
                        result.push(node);
                    }
                }
                return result;
            },
            createPostDirectory = function (article, directory, isDirNum) {
                let contentArr = [],
                    titleId = [],
                    levelArr, root, level,
                    currentList, list, li, link, i, len;
                levelArr = (function (article, contentArr, titleId) {
                    let titleElem = postChildren(article.childNodes, /^h\d$/),
                        levelArr = [],
                        lastNum = 1,
                        lastRevNum = 1,
                        count = 0,
                        guid = 1,
                        id = 'directory' + (Math.random() + '').replace(/\D/, ''),
                        num, elem;
                    while (titleElem.length) {
                        elem = titleElem.shift();
                        contentArr.push(elem.innerHTML);
                        num = +elem.tagName.match(/\d/)[0];
                        if (num > lastNum) {
                            levelArr.push(1);
                            lastRevNum += 1;
                        } else if (num === lastRevNum ||
                            num > lastRevNum && num <= lastNum) {
                            levelArr.push(0);
                            lastRevNum = lastNum;
                        } else if (num < lastRevNum) {
                            levelArr.push(num - lastRevNum);
                            lastRevNum = num;
                        }
                        count += levelArr[levelArr.length - 1];
                        lastNum = num;
                        elem.id = elem.id || (id + guid++);
                        titleId.push(elem.id);
                    }
                    if (count !== 0 && levelArr[0] === 1) levelArr[0] = 0;

                    return levelArr;
                })(article, contentArr, titleId);
                currentList = root = document.createElement('ul');
                let dirNum = [0];
                for (i = 0, len = levelArr.length; i < len; i++) {
                    level = levelArr[i];
                    if (level === 1) {
                        list = document.createElement('ul');
                        if (!currentList.lastElementChild) {
                            currentList.appendChild(document.createElement('li'));
                        }
                        currentList.lastElementChild.appendChild(list);
                        currentList = list;
                        dirNum.push(0);
                    } else if (level < 0) {
                        level *= 2;
                        while (level++) {
                            if (level % 2) dirNum.pop();
                            currentList = currentList.parentNode;
                        }
                    }
                    dirNum[dirNum.length - 1]++;
                    li = document.createElement('li');
                    link = document.createElement('a');
                    link.href = '#' + titleId[i];
                    link.innerHTML = !isDirNum ? contentArr[i] :
                        dirNum.join('.') + ' ' + contentArr[i];
                    li.appendChild(link);
                    currentList.appendChild(li);
                }
                directory.appendChild(root);
            };
        createPostDirectory(document.getElementById('post-content'), document.getElementById('directory'), true);
    };
    //构建预览
    postDirectoryBuild();
    //代码着色
    let blocks = document.querySelectorAll('pre code');
    for (let i = 0; i < blocks.length; i++) {
        hljs.highlightBlock(blocks[i]);
    }
    //下载按钮绑定
    $("#file-download").click(function () {
        let articleSeq = $("#file-download").attr("data");
        request({
            url: baseUrl + "/api/article/resources/" + articleSeq,
            method: 'get'
        }).then((response) => {
            if (response && response.code === 200) {
                preDownloadWindow(response.data)
            }
        }).catch(function (error) {
            console.log(error);
        });

    });

    function preDownloadWindow(resources) {
        let fileList = "";
        for (let resource of resources) {
            fileList += `<li>${resource.name}</li>`
        }
        let resourcesHtml = "<h2>文件列表</h2>" +
            "<div>" +
            "<ul>" +
            fileList +
            "</ul>" +
            "</div>";
        $.NZ_MsgBox.confirm({
            title: "确认开始下载?"
            , content: resourcesHtml
            , callback: function (confirm) {
                if (confirm) {
                    for (let resource of resources) {
                        downloadResource(resource)
                    }
                }
            }
        });

        function downloadResource(resource) {
            const element = document.createElement('a')
            element.href = resource.fileLocation;
            element.download = resource.name
            element.click()
        }
    }
})(jQuery);